;'use strict';
var tabSize = tabSize || {};
tabSize.init = function (id) {
    var i,
        self,
        table = document.getElementById(id),
        header = table.rows[0],
        tableX = header.clientWidth,
        length = header.cells.length;

    for (i = 0; i < length; i++) {
        header.cells[i].onmousedown = function () {
            self = this;
            if (event.offsetX > self.offsetWidth - 10) {
                self.mouseDown = true;
                self.oldX = event.x;
                self.oldWidth = self.offsetWidth;
            }
        };
        header.cells[i].onmousemove = function () {
            if (event.offsetX > this.offsetWidth - 10) {
                this.style.cursor = 'col-resize';
            } else {
                this.style.cursor = 'default';
            }
            if (self == undefined) {
                self = this;
            }
            if (self.mouseDown != null && self.mouseDown == true) {
                self.style.cursor = 'default';
                if (self.oldWidth + (event.x - self.oldX) > 0) {
                    self.width = self.oldWidth + (event.x - self.oldX);
                }
                self.style.width = self.width;
                table.style.width = tableX + (event.x - self.oldX) + 'px';
                self.style.cursor = 'col-resize';
            }
        };
        table.onmouseup = function () {
            if (self == undefined) {
                self = this;
            }
            self.mouseDown = false;
            self.style.cursor = 'default';
            tableX = header.clientWidth;
        };
    }
};

/**
 * 基于layui
 *
 * @param string id 容器ID
 * @param string url 配置接口
 * @param bool runQuery 是否运行查询
 */
var ulTable = function (id, url, runQuery) {
    this.id = id;
    this.url = url;
    this.runQuery = runQuery;
    this.fixed = false;
};

/**
 * 获取当前引入地址
 * @returns {*}
 */
ulTable.prototype.getPath = function () {
    var $ = this.$;
    var path = '';
    $('script').each(function () {
        var src = $(this).attr('src');
        if (src !== undefined && src !== null) {
            var index;
            if ((index = src.indexOf('ul-table.js')) >= 0) {
                path = src.substring(0, index);
            }
        }
    });
    return path;
};

/**
 * 初始化分页
 *
 */
ulTable.prototype.initPage = function () {
    this.page = 1;
    this.limit = 10;
};

/**
 * 开始函数
 *
 */
ulTable.prototype.run = function () {
    var that = this;
    layui.use(['jquery'], function () {
        that.$ = layui.jquery;
        that.path = that.getPath();
        that.rand = parseInt(Math.random() * 101, 10);

        that.getConfig(function (config) {
            // 初始化分页
            that.initPage();
            // 加载布局
            that.loadLayout(config, function () {
                // 加载表格模板
                that.loadTableTpl();
                // 加载添加模板
                that.loadInsertTpl();
                // 加载修改模板
                that.loadUpdateTpl();
                // 加载其他模板
                that.loadOtherTpl();
                // 加载查询
                that.loadSelectTpl(config);
                // 加载添加操作
                that.loadInsertOperate(config);
                // 加载修改操作
                that.loadUpdateOperate(config);
                // 加载删除操作
                that.loadDeleteOperate(config);
                // 加载其他操作
                that.loadOtherOperate(config);
            });
        })
    });
};

/**
 * 获取配置信息
 *
 * @param func
 */
ulTable.prototype.getConfig = function (func) {
    var that = this;
    that.$.ajax({
        type: "GET",
        url: that.url,
        async: true,
        dataType: 'json',
        success: function (result) {
            func(result);
        }
    });
};

/**
 * 加载布局
 *
 */
ulTable.prototype.loadLayout = function (config, func) {
    var that = this;
    layui.use(['jquery', 'laytpl', 'form'], function () {
        var $ = layui.jquery;
        var laytpl = layui.laytpl;
        var form = layui.form;
        $.ajax({
            type: "GET",
            url: that.path + "ul-tpl/layout.html?v=" + that.rand,
            async: false,
            success: function (result) {
                var string = laytpl(result).render(config);
                $("#" + that.id).html(string);
                form.render();
                func();
            }
        });
    });
};

/**
 * 加载表格模板
 *
 */
ulTable.prototype.loadTableTpl = function () {
    var that = this;
    that.$.ajax({
        type: "GET",
        url: that.path + "ul-tpl/table.html?v=" + that.rand,
        async: false,
        success: function (result) {
            that.tableTpl = result;
        }
    });
};


/**
 * 加载添加模板
 *
 */
ulTable.prototype.loadInsertTpl = function () {
    var that = this;
    that.$.ajax({
        type: "GET",
        url: that.path + "ul-tpl/insert.html?v=" + that.rand,
        async: false,
        success: function (result) {
            that.insertTpl = result;
        }
    });
};

/**
 * 加载修改模板
 *
 */
ulTable.prototype.loadUpdateTpl = function () {
    var that = this;
    that.$.ajax({
        type: "GET",
        url: that.path + "ul-tpl/update.html?v=" + that.rand,
        async: false,
        success: function (result) {
            that.updateTpl = result;
        }
    });
};

/**
 * 加载其他模板
 *
 */
ulTable.prototype.loadOtherTpl = function () {
    var that = this;
    that.$.ajax({
        type: "GET",
        url: that.path + "ul-tpl/other.html?v=" + that.rand,
        async: false,
        success: function (result) {
            that.otherTpl = result;
        }
    });
};


/**
 * 获取选中的
 *
 */
ulTable.prototype.getCheckedData = function () {
    var that = this;
    var data = [];
    that.$('[ul-checkbox-name=sub]:checked').each(function () {
        var index = that.$(this).attr('ul-index');
        data.push(that.queryData[index]);
    });
    return data;
}

/**
 * 加载查询
 *
 * @param config
 */
ulTable.prototype.loadSelectTpl = function (config) {
    var that = this;
    layui.use(['laytpl', 'form', 'laydate'], function () {
        var laytpl = layui.laytpl, form = layui.form, laydate = layui.laydate;

        that.$.ajax({
            type: "GET",
            url: that.path + 'ul-tpl/select.html?v=' + that.rand,
            async: true,
            success: function (result) {
                var data = [];
                if (config.select) {
                    data = config.select;
                }
                var string = laytpl(result).render(data);
                that.$("#ul-select").html(string);
                form.render();
                that.$("[ul-name=select][ul-type-name=time]").each(function () {
                    laydate.render({
                        elem: this,
                        type: 'datetime'
                    });
                });
                that.$('#ul-select-submit').bind('click', function () {
                    that.initPage();
                    that.selectOperate(config, true);
                })
                // 是否初始运行
                if (that.runQuery) {
                    that.selectOperate(config, true);
                }
            }
        });
    });
};

/**
 * 查询操作
 *
 */
ulTable.prototype.selectOperate = function (config, _first_query) {
    var that = this;
    layui.use(['laytpl', 'form', 'laypage', 'layer'], function () {
        var layer = layui.layer, laypage = layui.laypage, laytpl = layui.laytpl, form = layui.form;

        var index = layer.load(2, {time: 0});
        var data = {page: that.page, limit: that.limit};
        that.$('[ul-name=select]input').each(function () {
            data[that.$(this).attr('name')] = that.$(this).val();
        });
        that.$('[ul-name=select]select').each(function () {
            data[that.$(this).attr('name')] = that.$(this).val();
        });
        that.$.ajax({
            url: config['select-url'],
            type: 'POST',
            dataType: 'json',
            data: data,
            success: function (result) {
                layer.close(index);
                if (result.state) {
                    that.queryData = result.data;
                    laypage.render({
                        elem: 'ul-page'
                        , count: result.count,
                        curr: that.page,
                        limit: that.limit
                        , layout: ['prev', 'page', 'next', 'limit', 'skip', 'count']
                        , jump: function (obj, first) {
                            that.page = obj.curr;
                            that.limit = obj.limit;
                            // 首次不执行
                            if (!first) {
                                that.selectOperate(config);
                                that._first_query = false;
                            }
                        }
                    });
                    var string = laytpl(that.tableTpl).render({
                        'config': config,
                        'data': result.data,
                        'reg': /((http:)|(https:))[a-zA-Z\d\.\/\-\!\\\/\_\?\=\%]+/gi
                    });
                    that.$("#ul-table-content").html(string);
                    tabSize.init('ul-table-content');
                    // 图片浏览
                    layer.photos({
                        photos: '[ul-img=ul-img]'
                        , anim: 5 //0-6的选择，指定弹出图片动画类型，默认随机（请注意，3.0之前的版本用shift参数）
                    });

                    that.$('.ul-table-td-content').dblclick(function () {
                        var text = that.$(this).text();
                        var id = 'ul-edit-textarea' + new Date().getTime();
                        that.$(this).html('<textarea readonly id="' + id + '" class="layui-textarea">' + text + '</textarea>');
                        that.$('#' + id).focus();
                        that.$('#' + id).blur(function () {
                            text = that.$(this).parent().text();
                            that.$(this).parent().text(text);
                        });
                    });

                    form.render();
                    form.on('checkbox(ul-checkbox-head)', function (data) {
                        that.$('[ul-checkbox-name=sub]').prop('checked', data.elem.checked);
                        form.render('checkbox');
                    });

                    // 头部固定
                    that.fixedThead();
                } else {
                    layer.msg(result.msg);
                }
            },
            error: function () {
                layer.msg('网络错误：[查询数据]');
            }
        });
    });
};

/**
 * 添加操作
 *
 * @param config
 */
ulTable.prototype.loadInsertOperate = function (config) {
    var that = this;
    if (!config.insert) {
        return;
    }
    layui.use(['layer', 'laytpl', 'form', 'laydate', 'layedit'], function () {
        var layer = layui.layer, laytpl = layui.laytpl, form = layui.form, laydate = layui.laydate,
            layedit = layui.layedit;

        that.$('#ul-operate-insert').bind('click', function () {
            var string = laytpl(that.insertTpl).render(config.insert);
            var index_1 = layer.open({
                type: 1,
                title: '添加数据',
                content: string,
                area: '500px',
                offset: '100px',
                fixed: false,
                success: function () {
                    form.render();
                    that.$("[ul-name=insert][ul-type-name=time]").each(function () {
                        laydate.render({
                            elem: this,
                            type: 'datetime'
                        });
                    });

                    var layeditIndex = 0;
                    that.$("textarea[ul-name=insert][layedit]").each(function () {
                        var id = 'layedit-id-' + layeditIndex;
                        that.$(this).attr('id', id);
                        var index = layedit.build(id);
                        that.$(this).attr('index', index);
                    });

                    that.$('#ul-insert-submit').bind('click', function () {
                        layer.confirm('确认添加?', {title: '提示'}, function (index_2) {
                            layer.close(index_2);
                            var index_3 = layer.load(2, {time: 0});
                            // 参数组装
                            var data = {};
                            that.$('[ul-name=insert]input').each(function () {
                                data[that.$(this).attr('name')] = that.$(this).val();
                            });
                            that.$('[ul-name=insert]select').each(function () {
                                data[that.$(this).attr('name')] = that.$(this).val();
                            });
                            that.$('textarea[ul-name=insert][layedit]').each(function () {
                                data[that.$(this).attr('name')] = layedit.getContent(that.$(this).attr('index'));
                            });
                            that.$('textarea[ul-name=insert][textarea]').each(function () {
                                data[that.$(this).attr('name')] = that.$(this).val();
                            });

                            // 数据请求
                            that.$.ajax({
                                type: "POST",
                                url: config['insert-url'],
                                data: data,
                                async: true,
                                dataType: 'json',
                                success: function (result) {
                                    layer.close(index_3);
                                    if (result.state) {
                                        layer.msg('添加成功');
                                        layer.close(index_1);
                                        that.selectOperate(config);
                                    } else {
                                        layer.msg(result.msg);
                                    }
                                }, error: function () {
                                    layer.msg('网络错误：[添加数据]');
                                }
                            });
                        });
                    });
                }
            });
        });
    });
};

/**
 * 修改操作
 *
 * @param config
 */
ulTable.prototype.loadUpdateOperate = function (config) {
    var that = this;
    if (!config.update) {
        return;
    }
    layui.use(['layer', 'laytpl', 'form', 'laydate', 'layedit'], function () {
        var layer = layui.layer, laytpl = layui.laytpl, form = layui.form, laydate = layui.laydate,
            layedit = layui.layedit;
        that.$('#ul-operate-update').bind('click', function () {
            var checkedData = that.getCheckedData();
            if (checkedData.length != 1) {
                layer.msg('请选择要修改的数据行');
                return false;
            }
            var data = checkedData[0];
            var string = laytpl(that.updateTpl).render({config: config.update, data: data});
            var index_1 = layer.open({
                type: 1,
                title: '修改数据',
                content: string,
                area: '500px',
                offset: '100px',
                fixed: false,
                success: function () {
                    form.render();
                    that.$("[ul-name=update][ul-type-name=time]").each(function () {
                        laydate.render({
                            elem: this,
                            type: 'datetime'
                        });
                    });
                    var layeditIndex = 0;
                    that.$("textarea[ul-name=update][layedit]").each(function () {
                        var id = 'layedit-id-' + layeditIndex;
                        that.$(this).attr('id', id);
                        var index = layedit.build(id);
                        that.$(this).attr('index', index);
                        layeditIndex++;
                    });


                    that.$('#ul-update-submit').bind('click', function () {
                        layer.confirm('确认修改?', {title: '提示'}, function (index_2) {
                            layer.close(index_2);
                            var index_3 = layer.load(2, {time: 0});
                            // 参数组装
                            that.$('[ul-name=update]input').each(function () {
                                data[that.$(this).attr('name')] = that.$(this).val();
                            });
                            that.$('[ul-name=update]select').each(function () {
                                data[that.$(this).attr('name')] = that.$(this).val();
                            });
                            that.$('[ul-name=update][layedit]textarea').each(function () {
                                data[that.$(this).attr('name')] = layedit.getContent(that.$(this).attr('index'));
                            });
                            that.$('[ul-name=update][textarea]textarea').each(function () {
                                data[that.$(this).attr('name')] = that.$(this).val();
                            });
                            // 数据请求
                            that.$.ajax({
                                type: "POST",
                                url: config['update-url'],
                                data: data,
                                async: true,
                                dataType: 'json',
                                success: function (result) {
                                    layer.close(index_3);
                                    if (result.state) {
                                        layer.msg('修改成功');
                                        layer.close(index_1);
                                        that.selectOperate(config);
                                    } else {
                                        layer.msg(result.msg);
                                    }
                                }, error: function () {
                                    layer.close(index_3);
                                    layer.msg('网络错误：[修改数据]');
                                }
                            });
                        });
                    });
                }
            });
        });
    });
};

/**
 * 删除操作
 *
 * @param config
 */
ulTable.prototype.loadDeleteOperate = function (config) {
    var that = this;
    if (!config.delete) {
        return;
    }
    layui.use(['layer'], function () {
        var layer = layui.layer;
        that.$('#ul-operate-delete').bind('click', function () {
            var checkedData = that.getCheckedData();
            if (checkedData.length == 0) {
                layer.msg('请选择要删除的数据行');
                return false;
            }
            layer.confirm('确认删除选中项?', {title: '提示'}, function (index_2) {
                layer.close(index_2);
                var index_3 = layer.load(2, {time: 0});
                // 参数组装
                var data = {};
                for (var i = 0; i < checkedData.length; i++) {
                    for (var j = 0; j < config.delete.length; j++) {
                        var col = config.delete[j];
                        data[col + '[' + i + ']'] = checkedData[i][col];
                    }
                }
                // 数据请求
                that.$.ajax({
                    type: "POST",
                    url: config['delete-url'],
                    data: data,
                    async: true,
                    dataType: 'json',
                    success: function (result) {
                        layer.close(index_3);
                        if (result.state) {
                            layer.msg('删除成功');
                            that.selectOperate(config);
                        } else {
                            layer.msg(result.msg);
                        }
                    }, error: function () {
                        layer.close(index_3);
                        layer.msg('网络错误：[删除成功]');
                    }
                });
            });

        });
    });
};

/**
 * 其他操作
 *
 * @param config
 */
ulTable.prototype.loadOtherOperate = function (config) {
    var that = this;
    if (!config['other-operate']) {
        return;
    }
    for (var i = 0; i < config['other-operate'].length; i++) {
        var item = config['other-operate'][i];
        bindClick(item, i);
    }

    function bindClick(item, i) {
        layui.use(['layer', 'laytpl', 'form', 'layedit', 'laydate'], function () {
            var layer = layui.layer, laytpl = layui.laytpl, form = layui.form, layedit = layui.layedit,
                laydate = layui.laydate;

            if (item.url) {
                that.$('#ul-operate-other' + i).bind('click', function () {
                    var checkedData = that.getCheckedData();
                    if (checkedData.length == 0) {
                        layer.msg('请选择要' + item.title + '的数据行');
                        return false;
                    }
                    var data = checkedData[0];
                    var string = laytpl(that.otherTpl).render({config: item, data: data});
                    var index_1 = layer.open({
                        type: 1,
                        title: item.title + '数据',
                        content: string,
                        area: '500px',
                        offset: '100px',
                        fixed: false,
                        success: function () {
                            form.render();
                            that.$("[ul-name=other][ul-type-name=time]").each(function () {
                                laydate.render({
                                    elem: this,
                                    type: 'datetime'
                                });
                            });
                            var layeditIndex = 0;
                            that.$("textarea[ul-name=other][layedit]").each(function () {
                                var id = 'layedit-id-' + layeditIndex;
                                that.$(this).attr('id', id);
                                var index = layedit.build(id);
                                that.$(this).attr('index', index);
                                layeditIndex++;
                            });

                            that.$('#ul-other-submit').bind('click', function () {
                                layer.confirm('确认' + item.title + '选中的数据吗?', {title: '提示'}, function (index_2) {
                                    layer.close(index_2);
                                    var index_3 = layer.load(2, {time: 0});
                                    // 参数组装
                                    var data = {};
                                    for (var i = 0; i < checkedData.length; i++) {
                                        for (var j = 0; j < item['param'].length; j++) {
                                            var k = item['param'][j];
                                            data[k + '[' + i + ']'] = checkedData[i][k];
                                        }
                                    }
                                    // 参数组装
                                    that.$('[ul-name=other]input').each(function () {
                                        data[that.$(this).attr('name')] = that.$(this).val();
                                    });
                                    that.$('[ul-name=other]select').each(function () {
                                        data[that.$(this).attr('name')] = that.$(this).val();
                                    });
                                    that.$('[ul-name=other][layedit]textarea').each(function () {
                                        data[that.$(this).attr('name')] = layedit.getContent(that.$(this).attr('index'));
                                    });
                                    that.$('[ul-name=other][textarea]textarea').each(function () {
                                        data[that.$(this).attr('name')] = that.$(this).val();
                                    });

                                    // 数据请求
                                    that.$.ajax({
                                        type: "POST",
                                        url: item['url'],
                                        data: data,
                                        async: true,
                                        dataType: 'json',
                                        success: function (result) {
                                            layer.close(index_3);
                                            if (result.state) {
                                                layer.msg(item.title + '成功');
                                                layer.close(index_1);
                                                that.selectOperate(config);
                                            } else {
                                                layer.msg(result.msg);
                                            }
                                        }, error: function () {
                                            layer.close(index_3);
                                            layer.msg('网络错误：[' + item.title + '数据]');
                                        }
                                    });
                                });
                            });
                        }
                    });
                });
            } else {
                that.$('#ul-operate-other' + i).bind('click', function () {
                    var checkedData = that.getCheckedData();
                    window[item.method](checkedData);
                });
            }
        });
    }
};

ulTable.prototype.fixedThead = function () {
    var that = this;
    if (this.fixed) {
        var $table = that.$("#" + this.id).find('table');
        var docTop = $table.offset().top;
        var $thead = null;
        var widths = [];
        that.$(document).scroll(function () {
            var top = that.$(this).scrollTop();
            if (docTop - top < 0) {
                if ($thead == null) {
                    $thead = $table.find('thead').clone();
                    $table.find('thead').find('th').each(function () {
                        widths.push(that.$(this).width());
                    })
                    $thead.find('th').each(function () {
                        that.$(this).width(parseInt(widths.splice(0, 1)) + 1);
                    })
                    $thead.attr('fiex-thead', 'fiex-thead');
                    $thead.addClass('fiex-thead');
                    that.$('#ul-table-content').append($thead);
                }
            } else if ($thead != null) {
                $thead.remove();
                $thead = null;
            }
        });
    }
}